package com.github.tetrisgame.ui.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.github.tetrisgame.R;
import com.github.tetrisgame.databinding.ActivityLoginBinding;
import com.github.tetrisgame.databinding.ActivityMainBinding;
import com.github.tetrisgame.databinding.DialogChooseBinding;
import com.github.tetrisgame.manager.GameCenter;
import com.github.tetrisgame.utils.Communication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding mainBinding;
    private ActivityResultLauncher<Intent> cameraLauncher;
    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_READ_EXTERNAL_STORAGE_PERMISSION = 101;
    private ActivityResultLauncher<Intent> gallery;
    private ActivityResultLauncher<Uri> camera;
    private AlertDialog dialog;
    private String requiredPermission;
    File photoFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = ActivityLoginBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(mainBinding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initGallery();
        initDialog();
        initEvent();
        initCamera();
        /**
         * TODO template 如果是自定义短信模板，此处替换为你在控制台设置的自定义短信模板名称；如果没有对应的自定义短信模板，则使用默认短信模板。
         *
         */

    }

    private void initEvent() {
        mainBinding.button.setOnClickListener(v->{
            if (!mainBinding.checkBox2.isChecked()){
                ObjectAnimator translationAnim = ObjectAnimator.ofFloat(mainBinding.textView2, "translationX", 0, 25);
                ObjectAnimator translationAnimF = ObjectAnimator.ofFloat(mainBinding.textView2, "translationX", 25, 0);
                translationAnim.setDuration(100);
                translationAnimF.setDuration(100);
                for (int i = 0; i < 3; i++) {
                    translationAnim.start();
                    translationAnimF.start();
                }
                return;
            }
            String phoneNumber = mainBinding.name.getText().toString().trim();
            if(phoneNumber.length() == 11){
                send(phoneNumber);
                Communication.setOnPasswordInputListener(()->{
                    return phoneNumber;
                });
            }
        });
        mainBinding.head.setOnClickListener(v->{
            dialog.show();
        });
    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        DialogChooseBinding dialogChooseBinding = DialogChooseBinding.inflate(getLayoutInflater());
        builder.setView(dialogChooseBinding.getRoot());
        dialogChooseBinding.camera.setOnClickListener(v -> {
            try {
                checkCameraPermission();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        dialogChooseBinding.read.setOnClickListener(v -> {
            checkReadPermission();
        });
        //创建弹窗对象
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
    }
    //设置启动器,并且设置更换图片
    private void initGallery(){
        gallery = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result ->{
                    if(result.getResultCode() == RESULT_OK && result.getData() != null){
                        Uri selectedImage = result.getData().getData();
                        InputStream inputStream = null;
                        try {
                            inputStream = getContentResolver().openInputStream(selectedImage);
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
                        mainBinding.head.setImageBitmap(bitmap);
                    }
                }
        );
    }
    private void initCamera() {
        camera = registerForActivityResult(
                new ActivityResultContracts.TakePicture(),
                result -> {
                    if (result && photoFile != null) { // 确保拍照成功且文件存在
                        try {
                            // 直接从拍照保存的文件读取图片
                            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                            if (bitmap != null) {
                                mainBinding.head.setImageBitmap(bitmap); // 设置头像
                            } else {
                                Toast.makeText(this, "无法加载图片", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(this, "图片读取失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
    }
    //检查相机权限,若无用requestPermissions进行请求2
    private void checkCameraPermission() throws IOException {

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_MEDIA_IMAGES},
                    REQUEST_CAMERA_PERMISSION
            );
        }else{
            openCamera();
        }
    }

    //跳转至相机
    private void galleryAddPic() {

        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        gallery.launch(intent);
    }

    private void checkReadPermission(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requiredPermission = Manifest.permission.READ_MEDIA_IMAGES;
        } else {
            requiredPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }
        if(ContextCompat.checkSelfPermission(this, requiredPermission) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{requiredPermission},
                    REQUEST_READ_EXTERNAL_STORAGE_PERMISSION
            );
            Toast.makeText(this,"1111"+ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE),Toast.LENGTH_LONG).show();
        }else{
            galleryAddPic();
        }
    }

    private File createCameraFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File camersFile = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        return camersFile;
    }
    private void openCamera() throws IOException {
        // 1. 创建保存图片的临时文件（通过已有的 createCameraFile() 方法）
        photoFile = createCameraFile();
        if (photoFile == null) {
            Toast.makeText(this, "无法创建图片文件", Toast.LENGTH_SHORT).show();
            return;
        }

        // 2. 生成合法的 Uri（兼容 Android 7.0+ 的 FileProvider）
        Uri photoUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 注意：需要在 AndroidManifest 中配置 FileProvider（见步骤3）
            photoUri = FileProvider.getUriForFile(
                    this,
                    "com.github.tetrisgame.fileprovider", // 与清单文件中保持一致
                    photoFile
            );
        } else {
            // 低版本直接用文件路径生成 Uri
            photoUri = Uri.fromFile(photoFile);
        }

        // 3. 启动相机，传入正确的 Uri 用于保存图片
        camera.launch(photoUri);
    }
    private void send(String phoneNumber){
        BmobSMS.requestSMSCode(phoneNumber, "DataSDK", new QueryListener<Integer>() {
                      @Override
                      public void done(Integer smsId, BmobException e) {
                          if (e == null) {
                              Toast.makeText(LoginActivity.this,"发送验证码成功，短信ID：" + smsId + "\n",Toast.LENGTH_LONG).show();
                              Intent intent = new Intent(LoginActivity.this,verifyActivity.class);
                              intent.putExtra("phone",phoneNumber);
                              startActivity(intent);
                          } else {
                              Toast.makeText(LoginActivity.this,"发送验证码失败：" + e.getErrorCode() + "-" + e.getMessage() + "\n",Toast.LENGTH_LONG).show();
                          }
                      }
                  });
    }

}